﻿using log4net;
using SuperFx;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SuperMoney.AdPlatformCallback.Controllers
{
	/// <summary>
	/// 多盟广告回调控制器。
	/// </summary>
	public class DomobController : Controller
	{
		/*****************************************************************
		 * 多盟一个账户只能配置一个回调地址；
		 * 可以通过PublisherID来区分不同的应用；
		 *****************************************************************/

		const string secret_key = "b64980d8";
		const string adPlatform = "domob";
		const string iOS_PubId = "96ZJ1kWAze23HwTAw5";
		const string Android_PubId = "96ZJ0UEQze23HwTA7v";

		//
		// GET: /Domob/iOS

		public ActionResult iOS(string orderid, string pubid, int? adid, string ad, string user, string device, decimal? price, int? point, int? ts, string sign)
		{
			Dictionary<string, object> dict = new Dictionary<string, object>();
			foreach (var key in Request.QueryString.AllKeys)
			{
				if (key == "sign") continue;
				dict.Add(key, Request.QueryString[key]);
			}
			dict = dict.OrderBy(p => p.Key).ToDictionary(p => p.Key, p => p.Value);

			string str = null;
			foreach (var kv in dict)
			{
				string kvStr = String.Format("{0}={1}", kv.Key, kv.Value);
				if (str == null)
				{
					str = kvStr;
				}
				else
				{
					str += kvStr;
				}
			}
			str += secret_key;
			string sign_local = Md5Hash.Compute(str);
			// 签名验证
			if (sign == sign_local)
			{// 通过
				try
				{
					if (!adid.HasValue) adid = 0;
					if (!price.HasValue) price = 0;
					if (!point.HasValue) point = 0;
					if (!ts.HasValue) ts = 0;
					DateTime adOrderTime = new DateTime(1970, 1, 1).AddSeconds(ts.Value);

					string mrc_device = "";
					if (pubid == iOS_PubId)
					{
						mrc_device = "iOS";
					}
					else if (pubid == Android_PubId)
					{
						mrc_device = "Android";
					}

					AdRecordService.Instance.Create(adPlatform, orderid, adOrderTime, 0, device, adid.ToString(), ad, "0", point.Value, price.Value, pubid, mrc_device, user);
				}
				catch (Exception<AdRecordExistsExceptionArgs> ex)
				{
					LogManager.GetLogger("Domob").Error(orderid + "多盟广告记录已存在", ex);
					HttpContext.Response.StatusCode = 403;
				}
				catch (Exception ex)
				{
					LogManager.GetLogger("Domob").Error(orderid + "服务器端错误", ex);
					HttpContext.Response.StatusCode = 500;
				}
			}
			else
			{// 失败
				LogManager.GetLogger("Domob").Error(Request.Url + "签名验证不通过");
				HttpContext.Response.StatusCode = 400;
			}

			return new EmptyResult();
		}
	}
}
